<template>
  <div class="app-container">
    <div class="filter-container" style="margin-bottom:50px">
      <el-input v-model="listQuery.roleCode" placeholder="角色编号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.roleName" placeholder="角色名称" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      
      <!-- <el-select v-model="listQuery.roleState" placeholder="角色状态" clearable style="width: 140px" class="filter-item">
        <el-option v-for="item in stateOptions" :key="item" :label="item" :value="item" />
      </el-select> -->
      <el-button class="filter-item" type="primary" icon="el-icon-search" style="margin-left:200px" @click="handleFilter()">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="fetchData()">
        重置
      </el-button>
    </div>


    <el-row :gutter="10" class="mb8" style="margin-bottom:20px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          disabled
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          disabled
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          disabled
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          disabled
        >导出</el-button>
      </el-col>
    </el-row>

<!-- :data="list"  -->
<!-- :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)" -->
    <el-table 
        v-loading="listloading" 
        :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)" 
        element-loading-text="Loading"
        border
        highlight-current-row>

        <el-table-column align="center" label="序号">
          <template slot-scope="scope">
              {{ scope.row.roleId }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="角色编号">
          <template slot-scope="scope">
              {{ scope.row.roleCode }}
          </template>
        </el-table-column>
 
        <el-table-column align="center" label="角色名称">
          <template slot-scope="scope">
              {{ scope.row.roleName }}
            </template>
        </el-table-column>
 

        <!-- <el-table-column align="center" label="角色状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.roleState | stateFilter">
              {{ scope.row.roleState }}
            </el-tag>
          </template>
        </el-table-column> -->

        <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleEdit(row)" plain>
            配置路由
          </el-button>
          <!-- <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)" plain>
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,15,20,25.30]"
        :page-size="pagesize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total">
    </el-pagination>

    <!-- //对话框   -->
    <el-dialog :title="formTitle[dialogState]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色编号" prop="roleCode" label-width="80px">
          <el-input v-model="temp.roleCode" placeholder="请填写用户编号" disabled />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="temp.roleName" placeholder="请填写用户名称" disabled/>
        </el-form-item>


        <el-form-item label="路由菜单">
            <el-tree
              ref="tree"
              :check-strictly="checkStrictly"
              :data="routesData"
              :props="defaultProps"
              show-checkbox
              node-key="path"
              class="permission-tree"
            />
        </el-form-item>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogState==='add'?AddData():editData()">
          确认
        </el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { getList } from '@/api/userRole'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { addRoleInfo } from '@/api/userRole'
import { findRoleInfo } from '@/api/userRole'
import { getRouters,getAllRouters,updateRoutes} from '@/api/user'
import path from 'path'
// import { ElMessage, ElMessageBox } from 'element-plus'

const defaultRole = {
  routes: []
}

export default {
  components: { Pagination },
  //过滤器
  filters:{
    stateFilter(state){
      const stateMap = {
        启用:'success',
        禁用:'danger'
      }
      return stateMap[state]
    }
  },
  data() {
    return {
      role: Object.assign({}, defaultRole),
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      checkStrictly: false,
      routes: [],
      list:[],  //list:null
      total:0,
      listloading: true,
      dialogFormVisible: false,
      //查找
      listQuery:{
        roleCode:undefined,
        roleName:undefined
      },
      updateRoutes:[],
      //表格
      temp:{
        roleId:'',
        roleCode:'',
        roleName:''
      },
      // 校验规则
      rules:{
        //验证角色编号——只能数字+英文,不能包含特殊字符
        roleCode: [{ required: true, message: '用户编号不能为空', trigger: 'blur' },
          {pattern:/^[a-zA-Z0-9]+$/,message: '不能包含特殊字符', trigger: ['blur','change']},
          {min:2, max:6 ,message:'角色编号不少于2位不长于6位',trigger:['blur','change']}],
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' },
          {min:2, max:10 ,message:'角色名称不少于2位不长于10位',trigger:['blur','change']}]
      },
      //数据分页
      currentPage:  1,    //初始页
      pagesize: 5,      //每页的数据
      arr:[],    //你的数据
      stateOptions: ['启用', '禁用'],      //用户状态选择
      roles:['管理员','普通用户'],       //角色
      formTitle:{       //弹窗标题
        add:'新增角色信息',
        edit:'配置角色路由'
      },
      dialogState:''    //弹窗标题 
    }
  },

  computed: {
    routesData() {
      return this.routes
    }
  },

  created() {
    this.fetchData()
    console.log("currentPage",this.currentPage)
    console.log("pagesize",this.pagesize)
    this.getRoutes()
    // this.getRoles()
  },
  methods: {
    // async getRoles() {
    //   const res = await getRoles()
    //   this.rolesList = res.data.routers
    // },
    async getRoutes() {
      const res = await getAllRouters()
      this.serviceRoutes = res.data.routers
      this.routes = this.generateRoutes(res.data.routers)
    },
    //查找函数
    handleFilter() {
      console.log('我被点击了!')
      this.listloading = true
      findRoleInfo(this.listQuery).then(response =>{
        this.list = response.data.items
        this.total = response.data.total
        //消息提示
        this.$notify({
          title: 'Success',
          message: '查找成功',
          type: 'success',
          duration: 2000
        })
        console.log(this.list)
        this.listloading = false
      })
    },
    //每页显示几条
    handleSizeChange(val){
      this.pagesize = val;  //获取pagesize里的每页显示几条数据，赋给自定义的PageNUm
      console.log("当前页面显示xxx条",val);
      this.currentPage = 1;
    },
    //分页函数
    handleCurrentChange(val){
      this.currentPage = val;  
      console.log("当前页面显示xxx页",val)
    },  
    fetchData(){
        this.listloading = true
        getList().then(response =>{
            this.list = response.data.items
            this.total = response.data.total
            console.log(this.list)
            this.listloading = false
        })
    },
    //每次点击添加按钮重置表单
    resetTemp(){
      this.temp = {
        roleId:undefined,
        roleCode:'',
        roleName:''
      }
    },

    //编辑操作
    handleEdit(row){
      this.temp = Object.assign({}, row) // copy obj

      this.dialogState = 'edit'
      this.dialogFormVisible = true
      this.checkStrictly = true
      this.$nextTick(() => {
        getRouters(this.temp.roleId).then(response=>{

          const routes = this.generateRoutes(response.data.routers)
          //设置已有的结点
          this.$refs.tree.setCheckedNodes(this.generateArr(routes))

          console.log("所有的路由是",this.routes)
          console.log("该角色对应的路由为",routes)
          // this.routes = routes
          // this.checkStrictly = false
          console.log("点击编辑按钮后取得的对于路由",routes)
          // 设置节点的选中状态不影响其父节点和子节点
          this.checkStrictly = false
       })
      })
      // console.log("该行角色的角色id:",this.temp.roleId)
      console.log("编辑按钮被点击了")
      this.$nextTick(() => {
        //重置表单校验
        this.$refs['dataForm'].clearValidate()
      })
    },
    //编辑信息
    editData(){
      this.$refs['dataForm'].validate((valid)=>{
        if(valid){
          const tempData = Object.assign({}, this.temp)
          const checkedKeys = this.$refs.tree.getCheckedKeys()
          this.updateRoutes = checkedKeys
          console.log("temp数据",tempData)
          console.log("提交的路径信息",this.updateRoutes)
          console.log("对于的角色id",this.temp.roleId)
          updateRoutes(this.temp.roleId,this.updateRoutes).then(response =>{
            this.fetchData()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: response.message,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    //根据路由生成树型图
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        // 递归子路由
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    // Reshape the routes structure so that it looks the same as the sidebar
    // 重塑routes结构，使其看起来与边栏相同
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        // 跳过一些路由
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        // 递归子路由
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },

    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },

    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    // 参考src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      // 当只有一个子路由时，默认情况下会显示子路由
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      // 如果没有要显示的子路由，则显示父路由
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },

    //删除操作
    handleDelete(row,index){
      // this.dialogFormVisible = true
      //vue2直接用$confirm
      this.$confirm('是否删除该条信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //删除
          this.list.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      console.log("删除按钮被点击了")
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
